package com.example.supernote.ui.note.components

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import com.example.supernote.R
import com.example.supernote.data.network.config.getImageStyle
import com.example.supernote.model.note.context.Context
import com.example.supernote.ui.components.UniformDialog
import com.example.supernote.ui.components.UniformDropMenu
import com.example.supernote.ui.components.UniformPreviewBody
import com.example.supernote.ui.components.UniformPreviewFooter
import com.example.supernote.ui.components.UniformProgressBar
import com.example.supernote.ui.components.UniformToast
import com.example.supernote.ui.note.utils.getFinalTemplate
import com.example.supernote.ui.note.utils.isErrorMsg
import com.example.supernote.ui.utils.getShowInfos

@Composable
fun ShowGeneratorDialog(
    onCancel: () -> Unit,
    onGenerate: ((String) -> Unit, Map<String, String>) -> Unit,
    onConfirm: (aiCode: String) -> Unit,
    otherInfos: Map<String, String>
) {
    // 上下文环境
    val toastContext = LocalContext.current
    // 配置信息：otherInfos
    val dialogTitle = otherInfos["dialogTitle"]!!
    var config by remember { mutableStateOf(otherInfos["systemPrompt"]) }
    val showInfos = getShowInfos(dialogTitle)
    val targetName = stringResource(R.string.note_gen_image)
    // 答案模板, 用户prompt, 状态
    var template by remember { mutableStateOf("") }
    var prompt by remember { mutableStateOf("") }
    var isGenerated by remember { mutableStateOf(false) }
    var imageName: String by remember { mutableStateOf("") }
    // 生成图片的样式选项
    val styleChoice = getImageStyle()
    // 页面
    UniformDialog(
        title = dialogTitle,
        body = {
            // 用户 prompt 输入
            TextField(
                value = prompt,
                enabled = !isGenerated,
                onValueChange = { prompt = it },
                placeholder = {
                    Text(
                        text = otherInfos["inputLabel"]!!,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onBackground
                    )
                }
            )

            // 生成图片部分有额外的样式选择下拉框
            if (dialogTitle == targetName) {
                UniformDropMenu(
                    buttonModifier = Modifier.fillMaxWidth(),
                    itemsModifier = Modifier
                        .width((LocalConfiguration.current.screenWidthDp - 72).dp)
                        .heightIn(max = 300.dp),
                    menuItems = styleChoice,
                    menuButtonEnabled = !isGenerated,
                    menuButtonText = config!!,
                    onSelect = { key, _ ->
                        config = key
                    }
                )
            }

            // 展示返回结果
            if (template.isNotEmpty()) {
                val temp = getFinalTemplate(template)
                val canShowImage = dialogTitle == targetName && !isErrorMsg(temp)
                val getHtml: @Composable () -> String = {
                    if (canShowImage) {
                        val html = "<img src='$temp' style='width: 100%; height: auto;' />"
                        html
                    } else {
                        val ctx = Context()
                        ctx.article = TextFieldValue(temp)
                        ctx.parseContext()
                    }
                }

                UniformPreviewBody(
                    title = stringResource(R.string.note_preview_result),
                    html = getHtml(),
                )

                if (canShowImage) {
                    TextField(
                        value = imageName,
                        onValueChange = { imageName = it },
                        placeholder = {
                            Text(
                                text = showInfos["tip"]!!,
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onBackground
                            )
                        })
                }
            }

            if (isGenerated) {
                UniformProgressBar(showInfos["progressInfo"]!!)
            }
        }
    ) {
        val warn = stringResource(R.string.note_text_warning)
        // footer
        UniformPreviewFooter(
            template = getFinalTemplate(template),
            isGenerated = isGenerated,
            aiMode = showInfos["aiMode"]!!,
            confirmButtonText = showInfos["confirmButtonText"]!!,
            onCancel = onCancel,
            onConfirm = {
                onConfirm(template)
                if (showInfos["resultTip"] != "") {
                    UniformToast(toastContext, showInfos["resultTip"]!!)
                }
            }
        ) {
            // onGenerate()
            if (prompt.isEmpty()) {
                UniformToast(toastContext, warn)
            } else {
                template = ""
                isGenerated = true
                onGenerate({
                    template = it
                    isGenerated = false
                }, mapOf("prompt" to prompt, "systemPrompt" to if (dialogTitle == targetName) styleChoice[config]!! else config!!))
            }
        }
    }
}